package org.example.consumer.service;

import lombok.extern.slf4j.Slf4j;
import org.example.util.Constant;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 消费者服务
 *
 * @since 2022/7/12
 **/
@Service
@Slf4j
public class ConsumeService {

    public static final int count = 500;

    private static final ExecutorService executorService = Executors.newFixedThreadPool(4);

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // 添加数据到redis
    public void addToRedis() {
        // 操作Redis中的string类型的数据,先获取ValueOperation
        ListOperations<String, String> valueOperations = stringRedisTemplate.opsForList();
        while (true) {
            //获取数据到redis
            List<String> strings = valueOperations.rightPop(Constant.key, count);
            if (strings != null && strings.size() < count) {
                log.error("不够" + count + "，size为" + strings.size());
            }
        }
    }

    public Runnable getRunnable() {
        return new Runnable() {
            @Override
            public void run() {
                try {
                    addToRedis();
                } catch (Exception e) {
                    log.error("法生产欧五", e);
                }
            }
        };
    }

    public void run() {
        for (int i = 0; i < 4; i++) {
            executorService.submit(getRunnable());
        }
    }

}
